package com.panda.pandawash.activity;

import android.app.Activity;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.baidu.mapapi.SDKInitializer;
import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.BitmapDescriptor;
import com.baidu.mapapi.map.BitmapDescriptorFactory;
import com.baidu.mapapi.map.MapStatusUpdate;
import com.baidu.mapapi.map.MapStatusUpdateFactory;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.map.Marker;
import com.baidu.mapapi.map.MarkerOptions;
import com.baidu.mapapi.model.LatLng;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.panda.pandawash.R;
import com.panda.pandawash.application.CDApplication;
import com.panda.pandawash.bean.HttpResultBean;
import com.panda.pandawash.bean.PromoteBean;
import com.panda.pandawash.util.HttpUtil;
import com.panda.pandawash.view.StatusBarCompat;

import org.xutils.view.annotation.Event;
import org.xutils.view.annotation.ViewInject;
import org.xutils.x;

/**
 * Created by gaowf on 2017/2/21.
 */


public class PromoteActivity extends Activity implements BDLocationListener {

    @ViewInject(R.id.upload_promotion_tv)
    private TextView uploadTv;//提交按钮

    private final static String TAG = "PromoteActivity";

    MapView mapView;
    BaiduMap baiduMap;


    private LocationClient mLocationClient;//定位SDK的核心类
    public MyLocationListener mMyLocationListener;//定义监听类

    @ViewInject(R.id.store_address_name)
    public TextView mLocationResult;

    //为了不每次获取当前位置的时候都创建标记，将标记设置为成员变量
    private Marker mMarker;

    private EditText mStoreNameEdit;

    private String mStoreName = null;

    private String mLocationAddress = null;

    private String mLocationLatitude = null;

    private String mLocationLongitude = null;




    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        SDKInitializer.initialize(getApplicationContext());// 初始化操作,百度地图定位.
        setContentView(R.layout.feedback_baidumap_activity);
        x.view().inject(this);
        if(Build.VERSION.SDK_INT>= Build.VERSION_CODES.KITKAT) {
            StatusBarCompat.compat(this, getResources().getColor(R.color.colorPrimary));
        }

        /// 百度地图定位. @{
        mLocationClient = new LocationClient(this.getApplicationContext());
        mMyLocationListener = new MyLocationListener();
        mLocationClient.registerLocationListener(mMyLocationListener);

        initLocation();//初始化
        mLocationClient.start();

        mStoreNameEdit = (EditText) findViewById(R.id.enter_your_store_name);
        mapView = (MapView) findViewById(R.id.mapview);// 显示地图
        baiduMap = mapView.getMap();// 获取baiduMap对象

        //注册定位客户端，并且注册定位监听器
        mLocationClient = new LocationClient(this);
        mLocationClient.registerLocationListener(this);

        //InitLocation();//初始化
        //mLocationClient.start();

        initLocation2();
        mLocationClient.start();//注意这里 要用到 start而不是mLocationClient.requestLocation()
        /// 百度地图定位. @}

        uploadTv.setOnClickListener(mOnclickListener);
    }

    private void initLocation() {
        LocationClientOption options = new LocationClientOption();
        options.setLocationMode(LocationClientOption.LocationMode.Hight_Accuracy);//设置高精度定位定位模式
        options.setCoorType("bd09ll");//设置百度经纬度坐标系格式
        options.setScanSpan(1000);//设置发起定位请求的间隔时间为1000ms
        options.setIsNeedAddress(true);//反编译获得具体位置，只有网络定位才可以
        mLocationClient.setLocOption(options);
    }
    protected void initLocation2() {
        //创建定位客户端的选项，在这里面设置 定位的类型，CoorType，以及是否打开Gps，间隔事件ScanSpan
        LocationClientOption options = new LocationClientOption();
        //options.setLocationMode(LocationClientOption.LocationMode.Battery_Saving);
        options.setLocationMode(LocationClientOption.LocationMode.Hight_Accuracy);
        options.setCoorType("bd09ll");//latitue longtitute
        options.setScanSpan(5000);
        options.setIsNeedAddress(true);
        options.setOpenGps(true);
        options.setProdName("xueziqiang");
        //将定位的选项 赋值给 定位的客户端，并且 启动
        mLocationClient.setLocOption(options);
    }

    @Override
    protected void onResume() {
        super.onResume();
        mapView.onResume();
    }
    @Override
    protected void onStop() {
        super.onStop();
    }
    @Override
    protected void onPause() {
        super.onPause();
        mapView.onPause();
    }
    @Override
    protected void onDestroy() {
        super.onDestroy();
        mapView.onDestroy();

        mLocationClient.unRegisterLocationListener(this);
        //千万别忘了这个stop，如果不stop那么会继续执行
        mLocationClient.stop();
    }

    @Override
    public void onReceiveLocation(BDLocation bdLocation) {
        //注意 这个 LatLng，它用与设置 标记的位置和 Map的中心点的位置 。

        LatLng latLng = new LatLng(bdLocation.getLatitude(),bdLocation.getLongitude());
        if (mMarker == null) {
            MarkerOptions options = new MarkerOptions();
            options.position(latLng);
            options.draggable(true);
            //必须要设置option的icon，而且 这个 icon 必须是BitmapDescriptor的。
            BitmapDescriptor bitmapFactory = BitmapDescriptorFactory.fromResource(R.drawable.location);
            options.icon(bitmapFactory);
            //第一次的时候，通过强制类型转换将mMap.addOverlay(options) 变成Marker，因为它返回的其实是Overlay的Overlay和Marker的父类，所以要强制类型转换
            mMarker = (Marker) baiduMap.addOverlay(options);
        } else {
            mMarker.setPosition(latLng);
        }

        //设置获取的位置为中心点 。这里面的 参数是 LatLng
        MapStatusUpdate mapStatus = MapStatusUpdateFactory.newLatLng(latLng);
        baiduMap.setMapStatus(mapStatus);

    }

    @Override
    public void onConnectHotSpotMessage(String s, int i) {

    }

    //百度地图定位. @{
    /**
     * 实现实位回调监听
     */
    public class MyLocationListener implements BDLocationListener {

        public void onReceiveLocation(BDLocation location) {
            //Receive Location
            StringBuffer sb = new StringBuffer(256);
            sb.append("time : ");
            sb.append(location.getTime());//获得当前时间
            sb.append("\nerror code : ");
            sb.append(location.getLocType());//获得erro code得知定位现状
            sb.append("\nlatitude : ");
            sb.append(location.getLatitude());//获得纬度
            sb.append("\nlontitude : ");
            sb.append(location.getLongitude());//获得经度
            sb.append("\nradius : ");
            sb.append(location.getRadius());
            if (location.getLocType() == BDLocation.TypeGpsLocation){//通过GPS定位
                sb.append("\nspeed : ");
                sb.append(location.getSpeed());//获得速度
                sb.append("\nsatellite : ");
                sb.append(location.getSatelliteNumber());
                sb.append("\ndirection : ");
                sb.append("\naddr : ");
                sb.append(location.getAddrStr());//获得当前地址
                sb.append(location.getDirection());//获得方位
            } else if (location.getLocType() == BDLocation.TypeNetWorkLocation){//通过网络连接定位
                sb.append("\naddr : ");
                sb.append(location.getAddrStr());//获得当前地址
                //运营商信息
                sb.append("\noperationers : ");
                sb.append(location.getOperators());//获得经营商？
            }
            //logMsg(sb.toString());
            mLocationLongitude = location.getLongitude()+"";
            mLocationLatitude = location.getLatitude()+"";
            mLocationAddress = location.getAddrStr();
            logMsg(location.getAddrStr().toString());
        }

        @Override
        public void onConnectHotSpotMessage(String s, int i) {

        }
    }

    /**
     * 显示请求字符串
     * @param str
     */
    public void logMsg(String str) {
        Log.d("gwf_add", "Address = " + str);
        try {
            if (mLocationResult != null)
                mLocationResult.setText(str);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    /// 百度地图定位. @}

    @Event(R.id.feedback_baidumap_return)
    private void excuteReturn(View v) {
        finish();
    }

    private void promoteSend(){
        if(null !=mLocationAddress){
            String account = CDApplication.getIntance().getUserInfo().getUseraccount();
            mStoreName = mStoreNameEdit.getText().toString().trim();
            PromoteBean mPromoteBean = new PromoteBean();
            mPromoteBean.setLatitude(mLocationLatitude);
            mPromoteBean.setLongtitude(mLocationLongitude);
            mPromoteBean.setDescription(mLocationAddress);

            HttpUtil.promoteSubmit(new PromoteSendCallback(),account,account,mPromoteBean);
        }else{
            showMessage(getResources().getString(R.string.location_is_working));
        }

    }

    private View.OnClickListener mOnclickListener = new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            switch (view.getId()) {
                case R.id.upload_promotion_tv:
                    promoteSend();
                    break;
                default:
                    break;
            }
        }
    };

    private class PromoteSendCallback extends AsyncHttpResponseHandler {
        @Override
        public void onSuccess(int statusCode, String content) {
            super.onSuccess(statusCode, content);
            if (statusCode == 200) {
                HttpResultBean resultBean = HttpUtil.parserHttpResultInfo(content, null);
                Log.d(TAG, "resultBean = " + resultBean);
                if (resultBean != null) {
                    String code = resultBean.getCode();
                    String message = resultBean.getMessage();
                    Log.d(TAG, "code = " + code);
                    if(code.equals("0")){
                        showMessage(getResources().getString(R.string.promote_send_success));
                        CDApplication.getIntance().getPreferenceUtils().setBoolean("firstLogin",false);
                    }else if(code.equals("99")){
                        showMessage(message);
                    }
                }
            } else {
                showMessage(getResources().getString(R.string.promote_send_fail));
            }
        }

        @Override
        public void onFailure(Throwable error, String content) {
            super.onFailure(error, content);

            Log.d(TAG, "onFailure = " + error);
            if (error.toString().contains("refused")) {

            }
        }
    }

    private void showMessage(String string) {
        Toast toast = Toast.makeText(PromoteActivity.this, string, Toast.LENGTH_SHORT);
        toast.setGravity(Gravity.CENTER, 0, 0);
        toast.show();
    }

}
